package com.syqc.monitor.ui.newaddcar

import android.app.Activity
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.syqc.monitor.databinding.PopupPohotoImageBinding
import com.syqc.utils.GlideEngines

/**
 *@Author Jasper
 *@Time   2021/1/8
 *@Desc   图片选择
 */
class PhotoImagePopup(
    private val context: Activity,
    private var num: Int = 1,
    private val callback: (Int, ArrayList<LocalMedia>?) -> Unit
) : PopupWindow() {

    private val binding = PopupPohotoImageBinding.inflate(LayoutInflater.from(context))

    init {
        contentView = binding.root
        isClippingEnabled = false
        initView()
        setBackgroundDrawable(ColorDrawable(-0x56000000)) //设置背景
        width = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的宽
        height = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的高
    }

    fun initView() {
        binding.tvPopupPhotoCamera.setOnClickListener {
            val selectionModel = PictureSelector.create(context)
                .openCamera(SelectMimeType.ofImage())
            selectionModel.forResult(callbackListener)
            dismiss()
        }

        binding.tvPopupPhotoAlbum
            .setOnClickListener {
                //图片多选
                val selectionModel = PictureSelector.create(context)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideEngines.instance)
                    .isDisplayCamera(false)
                    .setMaxSelectNum(num)
                selectionModel.forResult(callbackListener)
                dismiss()
            }

        binding.tvPopupPhotoCancel.setOnClickListener {
            dismiss()
        }
    }

    private val callbackListener = object : OnResultCallbackListener<LocalMedia> {
        override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
            callback.invoke(1, result)
        }

        override fun onCancel() {
            callback.invoke(3, null)
        }

    }

    fun showAtLocation(num: Int) {
        this.num = num
        super.showAtLocation(context.window.decorView, Gravity.NO_GRAVITY, 0, 0)
    }

    fun setCancel(onClick: View.OnClickListener) {
        binding.tvPopupPhotoCancel.setOnClickListener {
            onClick.onClick(it)
            dismiss()
        }
    }
}